package com.lagou.rpc.consumer.client;


import org.apache.zookeeper.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;


@Component
public class WatcherApi implements Watcher {

       private static final Logger logger = LoggerFactory.getLogger(WatcherApi.class);

    @Autowired
    @Qualifier("zkClient")
    private ZooKeeper zkClient;

   @Override
   public void process(WatchedEvent event) {
       logger.info("【Watcher监听事件】={}",event.getState());
       logger.info("【监听路径为】={}",event.getPath());
       logger.info("【监听的类型为】={}",event.getType()); //  三种监听类型： 创建，删除，更新
       try {
           if (zkClient.exists("/server", false) == null) {
               zkClient.create("/server", "server".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
           }
       } catch (KeeperException e) {
           e.printStackTrace();
       } catch (InterruptedException e) {
           e.printStackTrace();
       }
       // 监听 /servers 节点
       List<String> children = null;
       try {
           children = zkClient.getChildren("/server", true);
       } catch (KeeperException e) {
           e.printStackTrace();
       } catch (InterruptedException e) {
           e.printStackTrace();
       }
       // 存储服务器节点主机名称集合
       ArrayList<String> hosts = new ArrayList<>();
       for (String child : children) {
           // 获取节点内容，即主机名称
           byte[] data = new byte[0];
           try {
               data = zkClient.getData("/server/" + child, false, null);
           } catch (KeeperException e) {
               e.printStackTrace();
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
           hosts.add(new String(data));
       }
       System.out.println("在线主机：" + hosts);
   }

   }



